
import { getConfigTask } from '../../api/task'
import { CONFIG_TASK, CONFIG_TASK_TOTAL_COUNT, CONFIG_TASK_PAGE_SIZE, CONFIG_TASK_HISTORY_DATA, CONFIG_TASK_CURRENT_PAGE } from '../motations-type'

export default {
  state: {
    configtask: [],
    configTaskTotalCount: null,
    configTaskPageSize: 20,
    configtaskHistoryData: [],
    currentPage: 1
  },
  getters: {
    configtask: state => state.configtask
  },
  mutations: {
    [CONFIG_TASK] (state, data) {
      state.configtask = data
    },
    [CONFIG_TASK_TOTAL_COUNT] (state, data) {
      state.configTaskTotalCount = data
    },
    [CONFIG_TASK_PAGE_SIZE] (state, data) {
      state.configTaskPageSize = data
    },
    [CONFIG_TASK_HISTORY_DATA] (state, data) {
      state.configtaskHistoryData = data
    },
    [CONFIG_TASK_CURRENT_PAGE] (state, data) {
      state.currentPage = data
    }
  },
  actions: {
    async getConfigTaskData ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getConfigTask(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          name: item.name,
          uname: item.uname,
          company: item.company,
          tel: item.tel,
          ctime: item.ctime.substring(0, 10),
          sharecnt: item.sharecnt,
          readcnt: item.readcnt
        }]
      })
      commit(CONFIG_TASK, newData)
      commit(CONFIG_TASK_TOTAL_COUNT, resp.data.data.total)
      if (newData.length < rootState.configtask.configTaskPageSize) {
        commit(CONFIG_TASK_HISTORY_DATA, newData)
      } else {
        commit(CONFIG_TASK_HISTORY_DATA, newData.slice(0, rootState.configtask.configTaskPageSize))
      }
      return resp
    },
    async changeConfigTaskPage ({ commit, rootState }, index) {
      let data = rootState.configtask.configtask
      let _start = (index - 1) * rootState.configtask.configTaskPageSize
      let _end = index * rootState.configtask.configTaskPageSize
      commit(CONFIG_TASK_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeConfigTaskPageSize ({ commit, rootState }, value) {
      commit(CONFIG_TASK_PAGE_SIZE, value)
    },
    async changeCurrentPage ({ commit, rootState }, value) {
      commit(CONFIG_TASK_CURRENT_PAGE, value)
    }
  }
}
